import cv2
import json
from PIL import Image, ImageDraw, ImageFont
import numpy as np

# ==== 1. 加载图像并转为 PIL 图像 ====
image_cv = cv2.imread('images/example.jpg')  # 改为你的图像路径
if image_cv is None:
    raise FileNotFoundError("图像未找到，请检查路径")

image_pil = Image.fromarray(cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(image_pil)

# ==== 2. 加载中文字体 ====
# 确保你有这个字体文件（Windows下一般有 SimHei.ttf）
font_path = "C:/Windows/Fonts/simhei.ttf"  # 改为你的中文字体路径
font = ImageFont.truetype(font_path, 20)

# ==== 3. 加载 JSON 标注数据 ====
with open('bbox_data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# ==== 4. 绘制框和中文说明 ====
for idx, obj in enumerate(data.get("objects", []), start=1):
    x1, y1, x2, y2 = obj["bbox"]
    desc = obj.get("description", f"ROI{idx}")

    # 红色矩形框
    draw.rectangle([x1, y1, x2, y2], outline="red", width=2)

    # 写中文说明
    text_pos = (x1, y1 - 25 if y1 - 25 > 5 else y1 + 5)
    draw.text(text_pos, desc, font=font, fill="red")

# ==== 5. 转回 OpenCV 图像格式并保存 ====
result_img = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
cv2.imshow("Labeled Image with Chinese", result_img)
cv2.imwrite("labeled_with_chinese.jpg", result_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
